package cn.edu.lingnan.util;

import java.sql.*;
import java.util.HashMap;

public class DBUtil {
    private static Connection conn = null;
    private static String DRIVER = null;
    private static String URL = null;
    private static String USERNAME = null;
    private static String PASSWORD = null;
    private static String xmlFileName = "database.conf.xml";
    private static String xsdFileName ="database.conf.xsd";

    static {
        String basePath=Thread.currentThread().getContextClassLoader().getResource("").getPath();
        xmlFileName = basePath+xmlFileName;
        xsdFileName = basePath+xsdFileName;
        if (XmIValidator.validate(xmlFileName,xsdFileName)) {//验证成功的情况下解析
            HashMap<String, String> hm = new HashMap<>();
            hm=XmlParser.parse(xmlFileName);
            DRIVER=hm.get("driver");
            URL=hm.get("url");
            USERNAME=hm.get("user");
            PASSWORD=hm.get("password");
        }
        //System.out.println(DRIVER+"//"+URL+"//"+USERNAME+"//"+PASSWORD);
    }

    private static DBUtil dbUtil;

    private DBUtil() {//构造方法初始化
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public static DBUtil getInstance() {
        if (dbUtil == null) {
            dbUtil = new DBUtil();
        }
        return dbUtil;
    }

    // 对外提供一个获取数据库连接的方法
    public Connection getConnection() {
        try {
            conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        }  catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return conn;
    }

    public void close(ResultSet rs, Statement stat, Connection conn){
        try {
            if (rs != null) {
                rs.close();
            }
            if(stat!=null){
                stat.close();
            }
            if(conn!=null){
                conn.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void close(ResultSet rs,PreparedStatement ps,Connection conn){
        try {
            if (rs != null) {
                rs.close();
            }
            if(ps!=null){
                ps.close();
            }
            if(conn!=null){
                conn.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
